<?php
/* 扫呗支付 */
namespace app\service;
use GuzzleHttp\Client;
use EasyWeChat\Factory;
use app\common\model\Order as OrderModel;
use app\common\model\ChatMoney as ChatMoneyModel;
use app\common\model\User as UserModel;
use app\common\model\ChatMsg as ChatMsgModel;
use app\common\model\Loginstatus;
use app\common\model\VideoPay as VideoPayModel;
class SbPayService extends BaseService
{
  public static $api = 'https://pay.lcsw.cn/lcsw/';//接口地址
  public static $key;//令牌
  public static $merchant_no;//商户号
  public static $terminal_id;//终端号
  public static $accessToken;
  public static $client;
  public static $payment;
  public  function __construct () {
    self::$key = 'de6f29f534a04b939736b4575729089f';
    self::$merchant_no = '834507298000002';//834507298000002 885200090000038
    self::$terminal_id = '11145811';
    self::$client = new Client(['base_uri' => self::$api]);

    $config = [
      'app_id' => config('authorizer_appid'),
      'mch_id' => config('wechat_mchid'),
      'key' => self::$key,
      'cert_path' => config('wechat_mchkeypem'),
      'key_path'  => config('wechat_mchcertpem'),
    ];
    self::$payment =  Factory::payment($config);
  } 
  /** 

  public static $api = 'http://test.lcsw.cn:8045/lcsw/';//接口地址
  public static $key;//令牌
  public static $merchant_no;//商户号
  public static $terminal_id;//终端号
  public static $accessToken;
  public static $client;
  public static $payment;
  public  function __construct () {
    self::$key = 'b9930b05ce4f488db4108c7eb7c83862';
    self::$merchant_no = '885200090000038';//834507298000002 885200090000038
    self::$terminal_id = '30057414';
    self::$client = new Client(['base_uri' => self::$api]);

    $config = [
      'app_id' => config('authorizer_appid'),
      'mch_id' => config('wechat_mchid'),
      'key' => self::$key,
      'cert_path' => config('wechat_mchkeypem'),
      'key_path'  => config('wechat_mchcertpem'),
    ];
    self::$payment =  Factory::payment($config);
  }
**/

  /* 退款接口 */
  public function wechatRefund ($orderInfo,$refund_no=false) {
    if(!$refund_no) {
      $refund_no = $order_sn.'_all';
    }
    $params = [
      'pay_ver' => '100',
      'pay_type' => '010',
      'service_id' => '030',
      'merchant_no' => self::$merchant_no,
      'terminal_id' => self::$terminal_id,
      'terminal_trace' => $refund_no,
      'terminal_time' => date('YmdHis'),
      'refund_fee' => (int)($orderInfo['pay_money']*100),
      'out_trade_no' => $orderInfo['sbpay_trade_no'],
    ];
    $params['key_sign'] = self::getSign($params);
    $response = self::$client->request('POST', 'pay/100/refund', [
      'json' => $params
    ]);
    $body = $response->getBody();
    $stringBody = (string)$body;
    $res = json_decode($stringBody,true);
    LogService::S()->writeLog('WechatPayRefundLog','',$stringBody);
    if($res['return_code']=='01' && $res['result_code']=='01') {
      return true;
    }
    return false;
  }


  /* 统一下单 */
  public  function wechatJssdk ($config) {
    $params = [
      'pay_ver' => '100',
      'pay_type' => '010',
      'service_id' => '012',
      'merchant_no' => self::$merchant_no,
      'terminal_id' => self::$terminal_id,
      'terminal_trace' => $config['out_trade_no'],
      'terminal_time' => date('YmdHis'),
      'total_fee' => (int)$config['total_fee'],
      'sub_appid' => 'wx639023a1ded5cf4b',
      'open_id' => $config['openid'],
      'order_body' => $config['body'],
      'notify_url' => $config['notify_url'],
      //'attach' => '',
      //'goods_detail' => '',
    ];
    //pr($params);
    $signArr = $params;
    unset($signArr['sub_appid']);
    unset($signArr['open_id']);
    unset($signArr['order_body']);
    unset($signArr['notify_url']);
    $params['key_sign'] = self::getSign($signArr);
    $response = self::$client->request('POST', 'pay/100/jspay', [
      'json' => $params
    ]);
    //pr($params);
    $body = $response->getBody();
    $stringBody = (string) $body;
      //return $stringBody;
      //$stringBody = '{"return_code":"01","return_msg":"预支付请求成功","result_code":"01","pay_type":"010","merchant_name":"技术部创建18(勿审核)","merchant_no":"885200090000038","terminal_id":"30057414","terminal_trace":"test-001","terminal_time":"20190612100419","total_fee":"1","out_trade_no":"300574140021319061210041800005","ali_trade_no":null,"appId":"wx639023a1ded5cf4b","timeStamp":"1560305058","nonceStr":"5MBv3PA3Hiirm77JsBxEeSl4BRRJcPSs","package_str":"prepay_id=wx12100418720847c3974758e11684874200","signType":"RSA","paySign":"mWV1PkAnNQ4I1JbqviZISQ2jvBwkQVqOoYOgvvnpZdwgo1vJBxhvgm9uYCvVsQ6T97dE3fPneDi7t0LZFJTalGAW23XV+nw2HMEjzqLne1q1NWJEfWiXmHFX15/0IWCy5LbuK6oXn5nC+PIZnMhLrACFqlSJxTVtT2iaN5FNyVE0rLfXvv/RknRTrBAnoP0rpbHDVCGEMhe/clxYQDY8QKL+De/yrU3pWy1ym8tQjltAuMlgx9UaVTjt8FdLpTohqqOTzp49UDx+VKUgSzZP+Xohe576XiEPW3g+mOO/YZ9T10cEj9I3gkSDhzZRVxU42+FnaRpGPA2G7Ao+VYUIzA==","token_id":null,"redirect_uri":null,"front_notify_url":null,"key_sign":"87342f850a24671554b18bca0d1b00a3","jdParams":null,"bestpayParams":null}';
    $res = json_decode($stringBody,true);
  
    if($res['return_code']=='01' && isset($res['package_str'])) {
    /*   return $res;
      $jsapi = self::$payment->jssdk->sdkConfig(str_replace('prepay_id=','',$res['package_str'])); 
      return $jsapi; */

      return [
        'appId' => $res['appId'],
        'timeStamp' => $res['timeStamp'],
        'timestamp' => $res['timeStamp'],
        'nonceStr' => $res['nonceStr'],
        'package' => $res['package_str'],
        'signType' => $res['signType'],
        'paySign' => $res['paySign']
      ];
    }
    return false;
  }

  /* 支付结果查询 */
  public function payQuery ($order_sn) {
    //terminal_trace
    $params = [
      'pay_ver' => '100',
      'pay_type' => '010',
      'service_id' => '020',
      'merchant_no' => self::$merchant_no,
      'terminal_id' => self::$terminal_id,
      'terminal_trace' => $order_sn,
      'terminal_time' => date('YmdHis'),
      'out_trade_no' => $order_sn,
    ];
    $params['key_sign'] = self::getSign($params);
    $response = self::$client->request('POST', 'pay/100/query', [
      'json' => $params
    ]);
    //pr($params);
    $body = $response->getBody();
    $stringBody = (string) $body;
    $res = json_decode($stringBody,true);
    if($res['return_code']=='01' && $res['result_code']=='01') {
      return true;
    }
    return false;
  }

  /* 签名 */
  public function getSign ($params) {
    $params['access_token'] = self::$key;
    $string = '';
    $index = 0;
    foreach($params as $k=>$v) {
      $index++;
      $string .= $k.'='.$v;
      if($index!=count($params)) {
        $string .= '&';
      }
    }
    return md5($string);
  }

  /* 核对签名 */
  public function checkSign ($arr) {
    $params = [
      'return_code' => $arr['return_code'],
      'return_msg' => $arr['return_msg'],
      'result_code' => $arr['result_code'],
      'pay_type' => $arr['pay_type'],
      'user_id' => $arr['user_id'],
      'merchant_name' => $arr['merchant_name'],
      'merchant_no' => $arr['merchant_no'],
      'terminal_id' => $arr['terminal_id'],
      'terminal_trace' => $arr['terminal_trace'],
      'terminal_time' => $arr['terminal_time'],
      'total_fee' => $arr['total_fee'],
      'end_time' => $arr['end_time'],
      'out_trade_no' => $arr['out_trade_no'],
      'channel_trade_no' => $arr['channel_trade_no'],
      'attach' => $arr['attach'],
    ];
    $sign = self::getSign($params);
    if($sign==$arr['key_sign']) {
      return true;
    }
    return false;
  }


/* 订单支付成功回调 */
public function wechatPaySuccess ($input) {
  LogService::S()->writeLog('WechatPayLog','',$input);
  $input = json_decode($input,true);
  $order = OrderModel::getOne([
    'order_sn' => $input['terminal_trace']
  ]);
  if(!$order || $order['checked']!=0) {
    exit(json_encode([
      'return_code' => '01',
      'return_msg' => '01'
    ]));
  }
  $payRes = self::checkSign($input);
  if($payRes) {
    OrderService::S()->changeOrder($order,[
      'checked' => 1,
      'pay_time' => time(),
      'sbpay_trade_no' => $input['out_trade_no']
    ]);
    exit(json_encode([
      'return_code' => '01',
      'return_msg' => '01'
    ]));
  }
}

  /* 微信发红包支付成功 */
  public function wechatMoneySuccess ($input) {
    LogService::S()->writeLog('WechatPayLog','',$input);
    $input = json_decode($input,true);
    $moneyLog = ChatMoneyModel::getOne([
      'order_sn' => $input['terminal_trace']
    ]);
    if(!$moneyLog || $moneyLog['status']!=0) {
      exit(json_encode([
        'return_code' => '01',
        'return_msg' => '01'
      ]));
    }
    $payRes = self::checkSign($input);
    if($payRes) {
      PayResultService::resultMoney($moneyLog);
      exit(json_encode([
        'return_code' => '01',
        'return_msg' => '01'
      ]));
    }
}

/* 视频课程购买成功 */
public function wechatVideoSuccess ($input) {
  LogService::S()->writeLog('WechatPayLog','',$input);
  $input = json_decode($input,true);
  $order = VideoPayModel::getOne([
    'order_sn' => $input['terminal_trace']
  ]);
  if(!$order || $order['status']!=0) {
    exit(json_encode([
      'return_code' => '01',
      'return_msg' => '01'
    ]));
  }

  $payRes = self::checkSign($input);
  if($payRes) {
    VideoPayModel::where([
      'id' => $order['id']
    ])->update([
      'status' => 1
    ]);
    exit(json_encode([
      'return_code' => '01',
      'return_msg' => '01'
    ]));
  }
}


}